package com.permission_demo.service;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.*;

@Slf4j
public class NoModelDataListener extends AnalysisEventListener<Map<Integer, String>> {

    private static final Map<Integer, String> HEAD_MAP = new LinkedHashMap<>();

    private static final Map<String, LinkedHashSet<String>> ROLE_PERMISSION_MAP = new LinkedHashMap<>();

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        log.info("表头:{}", JSON.toJSONString(headMap));
        HEAD_MAP.putAll(headMap);
    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        for (int i = 5; i < data.size(); i++) {
            Set<String> permissionSet = ROLE_PERMISSION_MAP.computeIfAbsent(HEAD_MAP.get(i), t -> new LinkedHashSet<>());
            if ("Y".equals(data.get(i))) {
                Objects.requireNonNull(permissionSet).add(String.join("$", data.get(0), data.get(1)));
            }
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        String fileName = "D:\\workspace\\idea_workspace\\idea_2022\\idea_2025_07\\permission_demo\\1.sql";
        File file = new File(fileName);

        try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file))) {
            Set<String> roleCodes = ROLE_PERMISSION_MAP.keySet();
            roleCodes.forEach(roleCode -> {
                try {
                    bufferedWriter.write(MessageFormat.format("SELECT @ROLE_ID_{0} := id FROM role WHERE role_code = ''{1}'';", roleCode, roleCode));
                    bufferedWriter.newLine();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            for (Map.Entry<String, LinkedHashSet<String>> entry : ROLE_PERMISSION_MAP.entrySet()) {
                StringBuilder stringBuilder = new StringBuilder();
                String k = entry.getKey();
                LinkedHashSet<String> v = entry.getValue();
                stringBuilder.append("---").append(k).append("---\r\n");
                stringBuilder.append(MessageFormat.format("DELETE FROM role_permission WHERE role_id = @ROLE_ID_{0};\r\n", k));
                for (String permission : v) {
                    String[] pArr = permission.split("\\$");
                    stringBuilder.append(MessageFormat.format("INSERT INTO role_permission(role_id,permission_id)  SELECT @ROLE_ID_{0}, id FROM permission WHERE c_code = ''{1}'' AND p_code = ''{2}'';\r\n", k, pArr[0], pArr[1]));
                }
                bufferedWriter.write(stringBuilder.toString());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        log.info("所有数据解析完成！");
    }

}
